<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="23">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="邮件服务器">
              <a-select v-model:value="listQuery.es_id" placeholder="请选择" style="width: 180px">
                <a-select-option key="" value=""> 全部服务器 </a-select-option>
                <a-select-option v-for="d in allServer" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="发送时间">
              <a-range-picker
                v-model:value="listQuery.send_time_range"
                show-time
                :presets="rangePresets"
                style="width: 370px"
              />
            </a-form-item>
            <a-form-item label="搜索项">
              <a-input
                v-model:value="listQuery.title"
                allowClear
                placeholder="输入收件人邮箱/标题/邮件内容搜索"
                style="width: 370px"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
            <a-form-item>
              <a-popconfirm
                title="请确认要删除记录的类型?"
                ok-text="删除所有记录"
                ok-type="danger"
                cancel-text="仅删除发送时间范围内的记录"
                okType="danger"
                :disabled="dataList['data'] == undefined || dataList['data'].length === 0"
                @confirm="clearAll"
                @cancel="clearBf"
              >
                <a-button
                  v-permission="{ action: 'del_all_email_log' }"
                  danger
                  type="link"
                  :disabled="dataList['data'] == undefined || dataList['data'].length === 0"
                >
                  批量删除
                </a-button>
              </a-popconfirm>
            </a-form-item>
            <a-form-item>
              <a-button
                v-permission="{ action: 'del_fail_email_log' }"
                type="link"
                danger
                @click="deleteFail"
              >
                删除失败记录
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="1">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template #summary>
        <a-table-summary fixed="bottom">
          <a-table-summary-row>
            <a-table-summary-cell :index="0" :col-span="2">
              <a-button
                v-permission="{ action: 'del_select_email_log' }"
                type="primary"
                danger
                :disabled="selectedRowKeys.length === 0"
                @click="deleteSelect"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除
              </a-button>
              <a-button
                v-permission="{ action: 'resend_select_email_log' }"
                type="primary"
                :disabled="selectedRowKeys.length === 0"
                style="margin-left: 10px"
                @click="reSendSelect"
              >
                <template #icon>
                  <SyncOutlined />
                </template>
                重发
              </a-button>
            </a-table-summary-cell>
          </a-table-summary-row>
        </a-table-summary>
      </template>
      <template #status="{ text: record }">
        <a-tag v-if="record.is_read == 1" color="green">已读</a-tag>
        <a-tooltip v-else-if="record.send_result == false">
          <template #title>{{ record.send_error }}</template>
          <a-tag color="red">发送失败</a-tag>
        </a-tooltip>
        <a-tag v-else>未读</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'email_log_view' }" @click="email_log_view(record)"> 详情 </a>
        <a-divider v-permission="{ action: 'email_log_ext' }" type="vertical" />
        <a-dropdown>
          <a v-permission="{ action: 'email_log_ext' }" class="ant-dropdown-link">
            更多
            <DownOutlined />
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'email_log_del' }" style="color: red">
                <a @click="email_log_delete(record)"> <DeleteOutlined /> 删除 </a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-drawer
      width="65%"
      title="邮件发送详情"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 8px"
          @click="
            () => {
              drawerShow = false
            }
          "
          >关闭</a-button
        >
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item label="ID">
          {{ FormState._id }}
        </a-form-item>
        <a-form-item label="标题">
          {{ FormState.title }}
        </a-form-item>
        <a-form-item label="邮箱">
          {{ FormState.email }}
        </a-form-item>
        <a-form-item label="用户名">
          {{ FormState.user_name }}
        </a-form-item>
        <a-form-item label="邮箱服务器ID">
          {{ FormState.es_id }}
        </a-form-item>
        <a-form-item label="邮件模板ID">
          {{ FormState.et_id }}
        </a-form-item>
        <a-form-item label="接口接收参数">
          {{ FormState.params }}
        </a-form-item>
        <a-form-item label="邮件内容">
          {{ FormState.content }}
        </a-form-item>
        <a-form-item label="邮件预览">
          <div v-html="FormState.send_content"></div>
        </a-form-item>
        <a-form-item label="发送时间">
          {{ FormState.send_time }}
        </a-form-item>
        <a-form-item label="阅读时间">
          {{ FormState.read_time }}
        </a-form-item>
        <a-form-item label="状态">
          <a-tag v-if="FormState.is_read == 1" color="green">已读</a-tag>
          <a-tooltip v-else-if="FormState.send_result == false">
            <template #title>{{ FormState.send_error }}</template>
            <a-tag color="red">发送失败</a-tag>
          </a-tooltip>
          <a-tag v-else>未读</a-tag>
        </a-form-item>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Image,
  Drawer,
  Switch,
  InputPassword,
  Popconfirm,
  InputNumber,
  Tooltip,
  RangePicker
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import {
  delEmailLog,
  getLogList,
  getAllServerList,
  delEmailLogBatch,
  delLogAll,
  delLogFail,
  reSendEmailBatch
} from '@/api/email'
import { useRouter } from 'vue-router'
import { requestFailed, requestSuccess } from '@/utils/feedback'
import { getRangeDateTime } from '@/utils/common'
import dayjs, { Dayjs } from 'dayjs'

export default defineComponent({
  name: 'EmailSendLog',
  components: {
    SyncOutlined,
    PlusOutlined,
    DownOutlined,
    EditOutlined,
    DeleteOutlined,
    [Row.name]: Row,
    [RangePicker.name]: RangePicker,
    [Popconfirm.name]: Popconfirm,
    [Tooltip.name]: Tooltip,
    [Drawer.name]: Drawer,
    [Switch.name]: Switch,
    [InputPassword.name]: InputPassword,
    [InputNumber.name]: InputNumber,
    [Col.name]: Col,
    [Image.name]: Image,
    [Divider.name]: Divider
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const dateFormat = 'YYYY-MM-DD HH:mm:s'
    const state = reactive<any>({
      loading: true,
      drawerShow: false,
      dataList: [],
      selectedRowKeys: [],
      selectedKeysPage: {},
      rangePresets: [
        { label: '近 7 天', value: [dayjs().add(-7, 'd'), dayjs()] },
        { label: '近 14 天', value: [dayjs().add(-14, 'd'), dayjs()] },
        { label: '近 30 天', value: [dayjs().add(-30, 'd'), dayjs()] },
        { label: '近 90 天', value: [dayjs().add(-90, 'd'), dayjs()] },
        { label: '近 180 天', value: [dayjs().add(-180, 'd'), dayjs()] }
      ],
      allServer: [],
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        es_id: '',
        send_time_range: [],
        send_time_ranges: [],
        title: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      columns: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: '对方邮箱',
          dataIndex: 'email'
        },
        {
          title: '标题',
          dataIndex: 'title'
        },
        {
          title: '发送内容',
          ellipsis: true,
          width: '700px',
          dataIndex: 'send_content'
        },
        {
          title: '状态',
          width: '70px',
          slots: { customRender: 'status' }
        },
        {
          title: '阅读时间',
          dataIndex: 'read_time'
        },
        {
          title: '发送时间',
          dataIndex: 'send_time'
        },
        {
          title: '操作',
          width: '150px',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getRangeDaySingle('')
      getServerDataList()
    })
    function getRangeDaySingle(operate) {
      let end = ''
      let start = ''
      end = getRangeDateTime(0)
      start = end
      start = getRangeDateTime(-7)
      state.listQuery.send_time_range = ref<[Dayjs, Dayjs]>([
        dayjs(start, dateFormat),
        dayjs(end, dateFormat)
      ])
      if (operate == 'auto') {
        setTimeout(() => {
          getDataList()
        }, 1000)
      } else {
        getDataList()
      }
    }

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }

    const FormState = reactive<any>({
      _id: '',
      title: '',
      tpl: '',
      status: ''
    })
    const FormRule = {
      title: [{ required: false, message: '请输入模板标题', trigger: ['blur', 'change'] }],
      tpl: [{ required: true, message: '请输入模板内容', trigger: ['blur', 'change'] }],
      status: [{ required: true, message: '请选择是否启用', trigger: ['blur', 'change'] }]
    }

    function reloadList(type = 'refresh') {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      state.selectedRowKeys = []
      if (type == 'refresh') {
        getRangeDaySingle('')
      } else {
        getDataList()
      }
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function getDataList() {
      state.listQuery.send_time_ranges[0] = state.listQuery.send_time_range[0].format(dateFormat)
      state.listQuery.send_time_ranges[1] = state.listQuery.send_time_range[1].format(dateFormat)
      getLogList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    function getServerDataList() {
      getAllServerList({}).then((res) => {
        state.allServer = res
      })
    }

    function email_log_test(itemData) {
      router.push({
        name: 'AdsAnalysis',
        query: { id: itemData._id, title: itemData.title + '（分类：' + itemData.cate + '）' }
      })
    }
    function email_log_view(res) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function addNewData() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerShow = true
    }
    function email_log_delete(data) {
      Modal.confirm({
        title: '确认永久删除所选记录?',
        content: '【' + data._id + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delEmailLog({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList('reload')
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function deleteSelect() {
      Modal.confirm({
        title: '确认批量删除所选项?',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delEmailLogBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList('reload')
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    function reSendSelect() {
      Modal.confirm({
        title: '确认重发所选项?',
        onOk() {
          reSendEmailBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList('reload')
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    const onSelectChange = (selectedRowKeys) => {
      state.selectedKeysPage[state.listQuery.pageNo] = selectedRowKeys
      let nowList: any[] = []
      for (const key in state.selectedKeysPage) {
        nowList = nowList.concat(state.selectedKeysPage[key])
      }
      const uniqueList = [...new Set(nowList)]
      state.selectedRowKeys = uniqueList
    }
    function clearAll() {
      Modal.confirm({
        title: '确认删除所有记录?',
        okType: 'danger',
        okText: '确认并立即删除',
        closable: true,
        keyboard: true,
        maskClosable: true,
        onOk() {
          state.listQuery['type'] = 'all'
          delLogAll(state.listQuery)
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList('reload')
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    function deleteFail() {
      Modal.confirm({
        title: '确认删除全部发送失败的记录?',
        content: '删除范围以当前所选邮件服务器为准 (清理失败记录会影响邮件统计，请悉知)',
        okType: 'danger',
        okText: '确认并删除',
        closable: true,
        keyboard: true,
        maskClosable: true,
        onOk() {
          delLogFail(state.listQuery)
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList('reload')
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    function clearBf() {
      Modal.confirm({
        title: '确认清除以下时间范围内的记录?',
        content: state.listQuery.send_time_ranges[0] + '至' + state.listQuery.send_time_ranges[1],
        okType: 'danger',
        okText: '确认并立即清除',
        closable: true,
        keyboard: true,
        maskClosable: true,
        onOk() {
          state.listQuery['type'] = 'time'
          delLogAll(state.listQuery)
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList('reload')
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    return {
      ...toRefs(state),
      handleTableChange,
      reloadList,
      searchSubmit,
      clearAll,
      clearBf,
      email_log_delete,
      deleteSelect,
      reSendSelect,
      formRef,
      onSelectChange,
      deleteFail,
      FormState,
      FormRule,
      addNewData,
      router,
      email_log_view,
      email_log_test,
      getDataList
    }
  }
})
</script>

<style scoped></style>
